﻿using DemoCore.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace DemoCore.Routings
{
    internal class RoutingManager
    {
        private List<RoutingFilter> filters = new List<RoutingFilter>();
        public static int MaxRetries = 3;
        public static RoutingManager Currrent = new RoutingManager();

        private RoutingManager()
        {
            var configSection = ConfigurationManager.GetSection("platform") as FilterSections;
            foreach (var obj in configSection.Filters)
            {
                FilterElement filterElement = (FilterElement)obj;
                this.filters.Add(new RoutingFilter
                {
                    Address = filterElement.Address,
                    Filter = filterElement.Filter,
                    Endpoint = filterElement.Endpoint
                });
            }
        }

        /// <summary>
        /// 获取要发送消息的Host信息
        /// 实现负载均衡
        /// </summary>
        /// <returns></returns>
        public HostInfo GetHost()
        {
            HostInfo host = HostManager.Default.GetHost();
            if (host == null)
                throw new Exception("没有可用的Host");
            return host;
        }

        /// <summary>
        /// 获取过滤器
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public RoutingFilter GetFilter(string filter)
        {
            RoutingFilter routingFilter = this.filters.FirstOrDefault(p => p.IsMatch(filter));
            if (routingFilter == null)
                throw new Exception("没有配置的Endpoint,Filter" + filter);
            return routingFilter;
        }

        /// <summary>
        /// 创建服务终结点网络地址
        /// </summary>
        /// <param name="host"></param>
        /// <param name="address"></param>
        /// <returns></returns>
        public EndpointAddress CreateEndpoint(HostInfo host, string address)
        {
            char[] trimChars = new char[]
            {
                '/',
                '\\'
            };
            return new EndpointAddress(host.Address?.TrimEnd(trimChars) + "/" + address.TrimStart(trimChars));
        }
    }
}
